package com.fjec.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fjec.common.convert.*;
import com.fjec.common.interceptor.SqlInjectInterceptor;
import com.fjec.common.spring.CustomRequestMappingHandlerAdapter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import java.util.List;

public class CommonWebMvcConfig extends WebMvcConfigurationSupport {

    private ObjectMapper objectMapper;

    public CommonWebMvcConfig(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        //检查Sql注入拦截器
        registry.addInterceptor(new SqlInjectInterceptor()).addPathPatterns("/**");
    }

    /**
     * 添加参数转换器
     */
    @Override
    protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new PaginationParamConvert());
        argumentResolvers.add(new JsonParameterConvert(objectMapper));
    }

    /**
     * 添加类型转换器
     */
    @Override
    protected void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToDateConvert());
        registry.addConverter(new StringToLocalDateConvert());
        registry.addConverter(new StringToLocalDateTimeConvert());
        registry.addConverterFactory(new StringToNumberConvert());
    }

    /**
     * 添加JSON类型转换器
     */
    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        JsonHttpMessageConvert convert = new JsonHttpMessageConvert();
        convert.setObjectMapper(objectMapper);
        converters.add(convert);
    }

    /**
     * 重写RequestMappingHandlerAdapter
     */
    @Override
    protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() {
        return new CustomRequestMappingHandlerAdapter();
    }

    /**
     * 设置允许跨域
     */
//    @Override
//    protected void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**")
//                //允许跨域的头信息
//                .allowedHeaders("*")
//                //允许跨域的Method
//                .allowedMethods("*")
//                //Access-Control-Max-Age 预检请求结果的缓存时间(秒)
//                .maxAge(1800)
//                //允许跨域的来源
//                .allowedOrigins("*")
//                //对许cookie
//                .allowCredentials(true);
//    }
}
